<template>
  <div class="report-container">
    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" ref="searchFormRef" :inline="true">
        <el-form-item label="统计维度" prop="dimension">
          <el-select v-model="searchForm.dimension" placeholder="请选择统计维度" style="width: 180px">
            <el-option label="按日统计" value="DAY" />
            <el-option label="按周统计" value="WEEK" />
            <el-option label="按月统计" value="MONTH" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围" prop="dateRange">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="物料类型" prop="materialType">
          <el-select v-model="searchForm.materialType" placeholder="请选择物料类型" clearable style="width: 180px">
            <el-option label="原材料" value="RAW_MATERIAL" />
            <el-option label="半成品" value="SEMI_FINISHED" />
            <el-option label="成品" value="FINISHED_PRODUCT" />
          </el-select>
        </el-form-item>
        <el-form-item label="仓库" prop="warehouse">
          <el-select v-model="searchForm.warehouse" placeholder="请选择仓库" clearable style="width: 180px">
            <el-option label="原料仓" value="RAW_WAREHOUSE" />
            <el-option label="成品仓" value="FINISHED_WAREHOUSE" />
            <el-option label="备件仓" value="SPARE_WAREHOUSE" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <el-button type="success" :icon="Download" @click="handleExport">导出报表</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value total-value">¥{{ statsData.totalValue }}</div>
              <div class="stat-label">库存总价值</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value turnover-rate">{{ statsData.turnoverRate }}</div>
              <div class="stat-label">库存周转率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value accuracy-rate">{{ statsData.accuracyRate }}%</div>
              <div class="stat-label">库存准确率</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-value shortage-count">{{ statsData.shortageCount }}</div>
              <div class="stat-label">缺货物料数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-container">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>库存价值趋势</span>
              </div>
            </template>
            <div ref="inventoryValueTrendChart" class="chart" style="height: 300px"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>物料类型分布</span>
              </div>
            </template>
            <div ref="materialTypeChart" class="chart" style="height: 300px"></div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px">
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>仓库库存对比</span>
              </div>
            </template>
            <div ref="warehouseCompareChart" class="chart" style="height: 300px"></div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="chart-card">
            <template #header>
              <div class="card-header">
                <span>出入库统计</span>
              </div>
            </template>
            <div ref="inOutStockChart" class="chart" style="height: 300px"></div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 详细数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>库存明细数据</span>
        </div>
      </template>

      <el-table :data="tableData" style="width: 100%" v-loading="loading" border>
        <el-table-column prop="date" label="日期" />
        <el-table-column prop="materialCode" label="物料编码" />
        <el-table-column prop="materialName" label="物料名称" />
        <el-table-column prop="materialType" label="物料类型">
          <template #default="scope">
            <el-tag :type="getMaterialTypeTag(scope.row.materialType)">
              {{ getMaterialTypeText(scope.row.materialType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse" label="仓库" />
        <el-table-column prop="currentStock" label="当前库存" align="right" />
        <el-table-column prop="safetyStock" label="安全库存" align="right" />
        <el-table-column prop="stockStatus" label="库存状态" align="center">
          <template #default="scope">
            <el-tag :type="getStockStatusTag(scope.row.stockStatus)">
              {{ getStockStatusText(scope.row.stockStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价" align="right">
          <template #default="scope"> ¥{{ scope.row.unitPrice }} </template>
        </el-table-column>
        <el-table-column prop="totalValue" label="库存价值" align="right">
          <template #default="scope"> ¥{{ scope.row.totalValue }} </template>
        </el-table-column>
        <el-table-column prop="lastInDate" label="最后入库日期" />
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.currentPage"
          :page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="inventoryReport">
import { ref, reactive, onMounted, nextTick } from "vue";
import type { FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Download } from "@element-plus/icons-vue";
import * as echarts from "echarts";

// 定义数据类型
interface InventoryData {
  date: string;
  materialCode: string;
  materialName: string;
  materialType: string;
  warehouse: string;
  currentStock: number;
  safetyStock: number;
  stockStatus: string;
  unitPrice: number;
  totalValue: number;
  lastInDate: string;
}

const loading = ref(false);
const tableData = ref<InventoryData[]>([]);
const searchFormRef = ref<FormInstance>();

// 图表引用
const inventoryValueTrendChart = ref();
const materialTypeChart = ref();
const warehouseCompareChart = ref();
const inOutStockChart = ref();

// 查询表单
const searchForm = reactive({
  dimension: "DAY",
  dateRange: [] as string[],
  materialType: "",
  warehouse: ""
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 统计数据
const statsData = reactive({
  totalValue: "2,580,000",
  turnoverRate: 4.2,
  accuracyRate: 98.5,
  shortageCount: 15
});

// 获取物料类型标签
const getMaterialTypeTag = (type: string) => {
  const typeMap: Record<string, string> = {
    RAW_MATERIAL: "primary",
    SEMI_FINISHED: "warning",
    FINISHED_PRODUCT: "success"
  };
  return typeMap[type] || "info";
};

// 获取物料类型文本
const getMaterialTypeText = (type: string) => {
  const typeMap: Record<string, string> = {
    RAW_MATERIAL: "原材料",
    SEMI_FINISHED: "半成品",
    FINISHED_PRODUCT: "成品"
  };
  return typeMap[type] || type;
};

// 获取库存状态标签
const getStockStatusTag = (status: string) => {
  const statusMap: Record<string, string> = {
    NORMAL: "success",
    LOW: "warning",
    SHORTAGE: "danger",
    OVERSTOCK: "info"
  };
  return statusMap[status] || "info";
};

// 获取库存状态文本
const getStockStatusText = (status: string) => {
  const statusMap: Record<string, string> = {
    NORMAL: "正常",
    LOW: "偏低",
    SHORTAGE: "缺货",
    OVERSTOCK: "积压"
  };
  return statusMap[status] || status;
};

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 库存价值趋势图
    if (inventoryValueTrendChart.value) {
      const trendChart = echarts.init(inventoryValueTrendChart.value);
      const trendOption = {
        tooltip: { trigger: "axis" },
        legend: { data: ["库存价值", "入库价值", "出库价值"] },
        xAxis: {
          type: "category",
          data: ["1月", "2月", "3月", "4月", "5月", "6月"]
        },
        yAxis: { type: "value" },
        series: [
          {
            name: "库存价值",
            type: "line",
            data: [2200000, 2350000, 2180000, 2420000, 2650000, 2580000]
          },
          {
            name: "入库价值",
            type: "bar",
            data: [850000, 920000, 780000, 1100000, 950000, 880000]
          },
          {
            name: "出库价值",
            type: "bar",
            data: [720000, 780000, 650000, 890000, 820000, 750000]
          }
        ]
      };
      trendChart.setOption(trendOption);
    }

    // 物料类型分布图
    if (materialTypeChart.value) {
      const typeChart = echarts.init(materialTypeChart.value);
      const typeOption = {
        tooltip: { trigger: "item" },
        legend: { orient: "vertical", left: "left" },
        series: [
          {
            name: "物料类型",
            type: "pie",
            radius: "50%",
            data: [
              { value: 1200000, name: "原材料" },
              { value: 680000, name: "半成品" },
              { value: 700000, name: "成品" }
            ]
          }
        ]
      };
      typeChart.setOption(typeOption);
    }

    // 仓库库存对比图
    if (warehouseCompareChart.value) {
      const warehouseChart = echarts.init(warehouseCompareChart.value);
      const warehouseOption = {
        tooltip: { trigger: "axis" },
        legend: { data: ["本月", "上月"] },
        xAxis: {
          type: "category",
          data: ["原料仓", "成品仓", "备件仓"]
        },
        yAxis: { type: "value" },
        series: [
          {
            name: "本月",
            type: "bar",
            data: [1200000, 700000, 680000]
          },
          {
            name: "上月",
            type: "bar",
            data: [1150000, 650000, 620000]
          }
        ]
      };
      warehouseChart.setOption(warehouseOption);
    }

    // 出入库统计图
    if (inOutStockChart.value) {
      const inOutChart = echarts.init(inOutStockChart.value);
      const inOutOption = {
        tooltip: { trigger: "axis" },
        legend: { data: ["入库数量", "出库数量"] },
        xAxis: {
          type: "category",
          data: ["周一", "周二", "周三", "周四", "周五", "周六"]
        },
        yAxis: { type: "value" },
        series: [
          {
            name: "入库数量",
            type: "bar",
            data: [320, 280, 350, 420, 380, 200]
          },
          {
            name: "出库数量",
            type: "bar",
            data: [280, 320, 300, 380, 350, 180]
          }
        ]
      };
      inOutChart.setOption(inOutOption);
    }
  });
};

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    // 模拟数据
    const mockData: InventoryData[] = [
      {
        date: "2024-01-15",
        materialCode: "RM001",
        materialName: "钢材Q235",
        materialType: "RAW_MATERIAL",
        warehouse: "原料仓",
        currentStock: 1500,
        safetyStock: 500,
        stockStatus: "NORMAL",
        unitPrice: 4500,
        totalValue: 6750000,
        lastInDate: "2024-01-10"
      },
      {
        date: "2024-01-15",
        materialCode: "SF001",
        materialName: "机械零件A",
        materialType: "SEMI_FINISHED",
        warehouse: "成品仓",
        currentStock: 200,
        safetyStock: 100,
        stockStatus: "NORMAL",
        unitPrice: 850,
        totalValue: 170000,
        lastInDate: "2024-01-12"
      },
      {
        date: "2024-01-15",
        materialCode: "FP001",
        materialName: "智能手机X1",
        materialType: "FINISHED_PRODUCT",
        warehouse: "成品仓",
        currentStock: 50,
        safetyStock: 100,
        stockStatus: "LOW",
        unitPrice: 2800,
        totalValue: 140000,
        lastInDate: "2024-01-08"
      },
      {
        date: "2024-01-15",
        materialCode: "RM002",
        materialName: "电子元件IC",
        materialType: "RAW_MATERIAL",
        warehouse: "原料仓",
        currentStock: 0,
        safetyStock: 200,
        stockStatus: "SHORTAGE",
        unitPrice: 25,
        totalValue: 0,
        lastInDate: "2023-12-28"
      },
      {
        date: "2024-01-15",
        materialCode: "FP002",
        materialName: "工业机器人A1",
        materialType: "FINISHED_PRODUCT",
        warehouse: "成品仓",
        currentStock: 80,
        safetyStock: 20,
        stockStatus: "OVERSTOCK",
        unitPrice: 85000,
        totalValue: 6800000,
        lastInDate: "2024-01-14"
      }
    ];

    tableData.value = mockData;
    pagination.total = mockData.length;
  } catch (error) {
    console.error("获取库存报表数据失败:", error);
    ElMessage.error("获取库存报表数据失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
  initCharts();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 导出报表
const handleExport = () => {
  ElMessage.info("导出库存报表功能开发中");
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
  initCharts();
});
</script>

<style scoped>
.report-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.stat-item {
  padding: 20px;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.total-value {
  color: #409eff;
}

.turnover-rate {
  color: #67c23a;
}

.accuracy-rate {
  color: #e6a23c;
}

.shortage-count {
  color: #f56c6c;
}

.charts-container {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>